package cn.bugstack.domain.strategy.service.rule.chain.factory;

import cn.bugstack.domain.strategy.model.entity.StrategyEntity;
import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 工厂，根据策略 ID（strategyId）构建对应的逻辑处理链（ILogicChain）
 */
@Service
public class DefaultChainFactory {

    //责任链节点的映射表，键为 String（规则名称），值为 ILogicChain（具体的逻辑处理节点）
    private final Map<String, ILogicChain> logicChainGroup;

    protected IStrategyRepository repository;


    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    /**
     * 通过 strategyId 获取对应的策略信息，并按照策略规则构建责任链
     * @param strategyId
     * @return LogicChain
     */
    public ILogicChain openLogicChain(Long strategyId) {
        // 1. 查询策略信息
        StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategy.ruleModels();
        if (null == ruleModels || 0 == ruleModels.length) return logicChainGroup.get("default");

        // 2. 获取第一个规则，作为责任链的起始节点
        ILogicChain logicChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain current = logicChain;

        // 3. 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            current = current.appendNext(nextChain); // 将下一个规则追加到当前责任链的末尾。
        }

        // 4. 追加默认规则作为兜底逻辑
        current.appendNext(logicChainGroup.get("default"));

        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }

}
